﻿using NxStoreManage;

using System;
using System.Diagnostics;
using System.IO;

namespace LengthAiCalculate
{
    public partial class DownFile : BaseForm
    {
        private readonly string SystemBit;

        public DownFile()
        {
            InitializeComponent();
            if (Environment.Is64BitOperatingSystem)
            {
                SystemBit = "64";
            }
            else
            {
                SystemBit = "32";
            }
            SetDataGridDefault(dataGridView1, rowHeadersVisible: false);
            this.Text += "(" + SystemBit + "位)";
        }

        private void DownFile_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = nxsqlHelper.GetDataTableFromSql($"SELECT [id],[aiFileTitle],[aiFileInfo],[aiFileName],[aiFileDownUrl],[systemBit] FROM[PM.AiMarket] WHERE systemBit='{SystemBit}'");
        }

        private void 下载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                ShowError("请选择要下载的模块!");
                return;
            }
            string url = dataGridView1.SelectedRows[0].Cells["aiFileDownUrl"].Value.ToString().Trim();
            string aiFileName = dataGridView1.SelectedRows[0].Cells["aiFileName"].Value.ToString().Trim();
            if (ServerFileUpDownload.DownloadFile(url, aiFileName, progressBar1))
            {
                this.Close();
                this.Dispose();
                ShowMsg("下载成功！");
            }
            else
            {
                ShowError("下载失败，文件未找到！");
            }
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            this.SetControlEnableState(false);
            string temp = StartupPath + $@"\vc_redist{SystemBit}.zip";
            if (ServerFileUpDownload.DownloadFile($"http://172.20.16.136/LengthAiCalculate/vc_redist{SystemBit}.zip", temp, progressBar1))
            {
                var (Flag, _) = ZipHelp.Compress(StartupPath + $@"\vc_redist{SystemBit}", temp, null);
                if (Flag)
                {
                    Process proc = new Process();
                    proc.StartInfo.FileName = StartupPath + $@"\vc_redist{SystemBit}\vc_redist{SystemBit}.exe";
                    proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(StartupPath + $@"\vc_redist{SystemBit}\");
                    proc.Start();
                    proc.WaitForExit();
                    ShowMsg("安装成功！");
                    this.Hide();
                    this.Dispose();
                }
            }
            else
            {
                ShowError("下载失败,文件未找到！");
            }
            this.SetControlEnableState(true);
        }
    }
}